﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.ServiceModel;
using WCFERP.PatcherContracts;
using System.Xml;
using System.IO;
using WCFMINERP.SharpZipLib;

namespace WCFMINERP.Patcher
{
    public partial class FrmUpdate : Form
    {
        public FrmUpdate()
        {
            InitializeComponent();
        }

        ChannelFactory<IPatcher> _proxyPacher;//创建代理
        IPatcher pacher;
        PatherInfo CurrPather = new PatherInfo();
        string updateFilePath = "";

        bool _Running = false;

        double NewClientVersion = 0;
        private void FrmUpdate_Load(object sender, EventArgs e)
        {


            _proxyPacher = new ChannelFactory<IPatcher>("Patcher");
            pacher = _proxyPacher.CreateChannel();//初始化网络联机
            backgroundWorkerUpdate.WorkerReportsProgress = true;
            backgroundWorkerUpdate.WorkerSupportsCancellation = true;
            //backgroundWorkerUpdate.RunWorkerAsync();
            XmlDocument xml = new XmlDocument();
            string xmlPath=Application.StartupPath + "\\ShopParameters.xml";
            if (!File.Exists(xmlPath))
            {
                XmlDocument xmldoc = new XmlDocument();

                //定义XML文档头文件
                XmlDeclaration xmlDeclaration = xmldoc.CreateXmlDeclaration("1.0", "utf-8", null);
                xmldoc.AppendChild(xmlDeclaration);
                //定义并添加XML的根
                XmlElement xmlroot = xmldoc.CreateElement("ShopParameters");
                xmldoc.AppendChild(xmlroot);
                XmlElement ClientVersion = xmldoc.CreateElement("ClientVersion");
                XmlText txClientVersion = xmldoc.CreateTextNode("1.0");
                ClientVersion.AppendChild(txClientVersion);
                XmlElement ProductVersion = xmldoc.CreateElement("ProductVersion");
                XmlText txProductVersion = xmldoc.CreateTextNode("0.0");
                ProductVersion.AppendChild(txProductVersion);
                xmlroot.AppendChild(ClientVersion);
                xmlroot.AppendChild(ProductVersion);
                xmldoc.Save(xmlPath);
            }
            xml.Load(Application.StartupPath + "\\ShopParameters.xml");
            string ClientVersionText = xml.SelectSingleNode(@"ShopParameters/ClientVersion").InnerText;
            try
            {
                //MessageBox.Show("当前版本" + ClientVersionText);  
                CurrPather = pacher.GetFileInfo((float)Convert.ToDecimal(ClientVersionText));///获取到当前更新包信息
                //MessageBox.Show("获取成功" + CurrPather.ClientVersion);                                                                            ///
            }
            catch (Exception exx)
            {
                //不需要更新直接运行主程序
                MessageBox.Show("远程连接车间失败，请联系车间","提示",MessageBoxButtons.OK,MessageBoxIcon.Information);
                this.Close();
            }
            if (CurrPather == null)
            {
                //不需要更新直接运行主程序
                System.Diagnostics.Process.Start(Application.StartupPath + "\\WCFMINERP.Update.exe");
                this.Close();
                return;
            }
            else
            {
                NewClientVersion = CurrPather.ClientVersion;
                timerLoad.Enabled = true;//激活下载事件
                //读取本地的文件件
               
                updateFilePath = Application.StartupPath + "\\update\\" + CurrPather.Name;//更新文件暂存位置
                if (File.Exists(updateFilePath))
                {
                    FileInfo info = new FileInfo(updateFilePath);
                    CurrPather.Offset = info.Length;
                }
                else
                {
                   
                    CurrPather.Offset = 0;
                }
                label1.Text = "正在下载" + CurrPather.Offset + "/" + CurrPather.Length;
            }

        }
        bool _updateSucess = false;
        private void backgroundWorkerUpdate_DoWork(object sender, DoWorkEventArgs e)
        {
            while (CurrPather.Offset < CurrPather.Length)
            {
                PatherInfo info = pacher.DownloadFile(CurrPather);
                FileStream fs = new FileStream(updateFilePath, FileMode.OpenOrCreate);//打开文件
                long offset = CurrPather.Offset;  //file.Offset 文件偏移位置,表示从这个位置开始进行后面的数据添加
                BinaryWriter writer = new BinaryWriter(fs);//初始化文件写入器
                writer.Seek((int)offset, SeekOrigin.Begin);//设置文件的写入位置
                writer.Write(info.Data);//写入数据
                CurrPather.Offset = fs.Length;
                fs.Close();
                backgroundWorkerUpdate.ReportProgress((int)(CurrPather.Offset / CurrPather.Length), CurrPather);
                
            }
            //MessageBox.Show("下载成功");  
            if (CurrPather.Offset >= CurrPather.Length)
            {
                //解压dao文件
                string extraceZipFile=updateFilePath.Substring(0,updateFilePath.LastIndexOf("\\")+1) +"current";
                //if (File.Exists(unZipFile))
                //{
                //    File.Delete(unZipFile);
                //}
                string appPath = Application.StartupPath;
                UnZipClass.ExtractZip(updateFilePath, extraceZipFile);
                DirectoryInfo dir = new DirectoryInfo(extraceZipFile);
                foreach (FileInfo file in dir.GetFiles())
                {
                    backgroundWorkerUpdate.ReportProgress(100, "正在更新文件..." + file.Name);
                    string NewFile = appPath + file.Name;
                    if (File.Exists(NewFile))
                    {
                        try
                        {
                            File.Delete(NewFile);
                        }
                        catch
                        {
 ///覆盖不成功，强制结束掉主线程后继续更新
 
                        }
                    }
                    File.Copy(file.FullName, appPath +"\\"+ file.Name,true);

 
                }
                if (NewClientVersion != 0)
                {
                    //MessageBox.Show("更新XML");  
                    string xmlPath = Application.StartupPath + "\\ShopParameters.xml";
                    UpdateNodesValue(@"ShopParameters/ClientVersion", xmlPath, NewClientVersion.ToString("0.0"));
                    //MessageBox.Show("更新完成!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                _updateSucess = true;
                
                
               // System.Diagnostics.Process.Start(Application.StartupPath + "\\WCFMINERP.Update.exe");

            }
        }

        private void backgroundWorkerUpdate_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            _Running = false ;
            //更新完成结束更新程序
            //本地XML写入
           
            //if (NewClientVersion != 0)
            //{
            //    UpdateNodesValue(@"ShopParameters/ClientVersion", xmlPath, NewClientVersion.ToString());
            //    MessageBox.Show("更新完成!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            //}
            if (_updateSucess)
            {
                System.Diagnostics.Process.Start(Application.StartupPath + "\\WCFMINERP.Update.exe");
                this.Close();
            }
           
        }
        public static void UpdateNodesValue(string nodesPath, string xmlPath, string nodesValue)
        {

            XmlDocument xmldoc = new XmlDocument();
            xmldoc.Load(xmlPath);

            xmldoc.SelectSingleNode(nodesPath).InnerText = nodesValue;
            xmldoc.Save(xmlPath);


        }
        private void backgroundWorkerUpdate_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            if (e.ProgressPercentage != 100)
            {
                label1.Text = "正在下载..." + e.ProgressPercentage * 100 + "%";
            }
            else
            {
 
            }

        }

        private void timerLoad_Tick(object sender, EventArgs e)
        {
            if (!_Running)
            {
                try
                {
                    _Running = true;
                    backgroundWorkerUpdate.RunWorkerAsync();
                }
                catch(Exception exx)
                {
                    label1.Text = "更新时出错，请参考" + exx.Message;
                    _Running = false;
                }
               
            }
        }

    }
}
